﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Reflection;
using System.Web.Routing;

namespace Lilium.Web.Mvc
{
	using Configuration;
	using System.Diagnostics;
	using System.Web;

	/// <summary>
	/// 
	/// </summary>
	/// <remarks>
	/// This controller is loaded by <see cref="DefaultControllerFactory "/>
	/// </remarks>
	public class ScriptResourceController: ControllerBase
	{
		static ScriptResourceController()
		{
			var configuration = MvcConfigurationSection.GetMvcConfigurationSection();
			m_ResourceLibraries = configuration.ResourceLibraries.ToDictionary(e => e.Name, e => e.GetScriptResourceLibrary());
			m_ScriptResourceControllerName = configuration.ScriptResourceController;
		}

		protected override void ExecuteCore()
		{
			var libraryName = ControllerContext.RouteData.GetRequiredString("action");
			ScriptResourceLibrary library;
			if (ResourceLibraries.TryGetValue(libraryName, out library))
				library.ProcessRequest(ControllerContext);
			else
				throw new InvalidOperationException(string.Format(Resources.Culture, Resources.ScriptResourceController_ResourceLibraryNotFound_0libraryName, libraryName));
		}

		#region public static string ScriptResourceControllerName

		private static readonly string m_ScriptResourceControllerName;

		public static string ScriptResourceControllerName { [DebuggerNonUserCodeAttribute] get { return m_ScriptResourceControllerName; } }

		#endregion

		#region private static Dictionary<string, string> ResourceLibraries

		private static readonly Dictionary<string, ScriptResourceLibrary> m_ResourceLibraries;

		private static Dictionary<string, ScriptResourceLibrary> ResourceLibraries { [DebuggerNonUserCodeAttribute] get { return m_ResourceLibraries; } }

		#endregion
	}
}